package br.facet.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.facet.pojo.Loja;
import br.facet.utils.HibernateUtils;

public class LojaDAO {

	public void salvar(Loja loja) throws Exception {
		Session sessao = null;
		Transaction tx = null;

		try {
			sessao = HibernateUtils.getSession();
			tx = sessao.beginTransaction();
			sessao.save(loja);
			tx.commit();

		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			if (sessao != null) {
				try {
					sessao.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}

	}

	public List<Loja> listar() {
		Session sessao = null;
		Transaction tx = null;
		List<Loja> lista = new ArrayList<Loja>();

		try {
			sessao = HibernateUtils.getSession();
			tx = sessao.beginTransaction();
			lista = sessao.createCriteria(Loja.class).list();

		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			if (sessao != null) {
				try {
					sessao.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		return lista;
	}

	public Loja load(Integer id) throws Exception {
		Session sessao = null;
		Transaction tx = null;
		Loja result = null;

		try {
			sessao = HibernateUtils.getSession();
			tx = sessao.beginTransaction();
			result = (Loja) sessao.load(Loja.class, id);
		} catch (Exception e) {
			tx.rollback();
			throw new Exception("Erro ao carregar a loja");
		} finally {
			sessao.close();
		}
		return result;
	}

	public void excluir(Loja loja) throws Exception {
		Session session = HibernateUtils.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.delete(loja);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			throw new Exception("Erro ao excluir a loja. Tente novamente.");
		} finally {
			session.close();
		}
	}
}
